package com.company.finance.ddd.domain.core.voucher.event.publisher;

import com.company.finance.ddd.domain.core.voucher.event.Event;
import com.company.finance.ddd.domain.core.voucher.event.handler.EventHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Observable;

/**
 *
 * @author wanglei
 * @version $$Id: AccountingDocumentEventPublisher, v 0.1 2021/2/3 10:48 Exp $$
 */
@Slf4j
@Component
public class VoucherEventPublisher extends Observable implements EventPublisher, ApplicationContextAware {

    @Override
    public void publish(Event event) {
        setChanged();
        try {
            notifyObservers(event);
        } catch (Exception e) {
            log.info("Handler throw exception.", e);
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        applicationContext.getBeansOfType(EventHandler.class).forEach((key, value) -> {
            addObserver(value);
        });
    }
}
